﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using RGBFinder.Resources;
using Microsoft.Phone.Tasks;
using System.Threading;
using System.Xml.Serialization;
using System.Text;
using System.Security.Cryptography;
using mmiWP7SDK;
using Microsoft.Advertising.Mobile.UI;

namespace RGBFinder
{
    public enum SetType
    {
        None,
        Red,
        Green,
        Blue
    }
    public enum GameDifficulty
    {
        Easy,
        Normal,
        Hard
    }

    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor



        public static string Global_Ranking = "";
        
        public static bool showScores = false;
        
        public MainPage()
        {
            InitializeComponent();

            DataContext = App.ViewModel;
            Ads_List.ItemsSource = App.ViewModel.Ads;
            Scores_List.ItemsSource = App.ViewModel.Scores;
            GameType_List.ItemsSource = App.ViewModel.GameTypes;
            AdControl.TestMode = false;

        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (!App.ViewModel.IsDataLoaded)
            {
                App.ViewModel.LoadData();
                new Thread(new ThreadStart(
                () =>
                {
                    WebConnection.updateOtherProduct(() =>
                    {
                        Dispatcher.BeginInvoke(() =>
                        {
                            App.ViewModel.Ads.Clear();
                            foreach (var app in StateAndOptions.state.applications2)
                            {
                                App.ViewModel.Ads.Add(new AdsViewModel() { Name = app.name, Description = app.description, ID = app.id, ImageUri = new Uri(app.imageUri, UriKind.Absolute) });
                            }
                            StateAndOptions.SaveState();
                        });
                    });
                })).Start();
            
            }


            Version_Area.Text = Strings.Version + (App.isTrial() ? "Trial" : "1.0");
            if (App.isTrial())
            {
                //Suggestion_Area.Visibility = System.Windows.Visibility.Collapsed;
                Suggestion_Button.Visibility = System.Windows.Visibility.Collapsed;
            }
            
            //Scores = Scoreboard.LoadScores();
            //Scores.Add(new Score() { time = "00:00:00", tests = 100, score = 100000, name = "Francesco" });
            App.ViewModel.Scores.Clear();


            //App.ViewModel.Scores.Add(new ScoresViewModel() { Index = Strings.Rank, Name = Strings.Name, Score = Strings.Score });
            var scores = StateAndOptions.state.scores.OrderByDescending(s=>s.score).ToList();
            for(int i=0; i<scores.Count; i++)
            {
                App.ViewModel.Scores.Add(new ScoresViewModel() { Index = "" + (i + 1), Name = scores[i].name, Level = scores[i].level, Score = "" + scores[i].score });
            }


        }
        
        private void OpenCredits_Button_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/CreditsPage.xaml", UriKind.Relative));
        }
        
        private void ClearScore_Button_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show(Strings.AreYouSureToClear, Strings.ClearScore, MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                //Scoreboard.DeleteScores();
                App.ViewModel.Scores.Clear();
            }
        }

        private void Suggestion_Button_Click(object sender, RoutedEventArgs e)
        {
            EmailComposeTask etc = new EmailComposeTask();
            etc.Subject = Strings.Title + " - " + Strings.Suggestion;
            etc.To = "luckmanera@gmail.com";
            etc.Show();
        }


        #region ADS



        public static bool showProducts = false;



        private void Ads_List_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (Ads_List.SelectedItem == null)
                return;
            AdsViewModel ads = Ads_List.SelectedItem as AdsViewModel;
            Ads_List.SelectedItem = null;
            if (ads.Name != Strings.OtherProducts && ads.ID != "")
                OpenMarket(ads.ID);


        }


        private void Ads1_Button_Click(object sender, RoutedEventArgs e)
        {
            PivotControl.SelectedItem = AdsPivot_Name;
        }

        private void OpenMarket(string ID)
        {

            MarketplaceDetailTask marketplaceDetailTask = new MarketplaceDetailTask();
            marketplaceDetailTask.ContentIdentifier = ID;
            marketplaceDetailTask.Show();
        }
        #endregion

        private void GameType_List_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (GameType_List.SelectedItem == null)
                return;
            var item = GameType_List.SelectedItem as GameTypeViewModel;
            var s = item.Name;
            if (s == Strings.Easy)
            {
                StateAndOptions.state.last_difficulty = GameDifficulty.Easy;
            }
            else if (s == Strings.Normal)
            {
                StateAndOptions.state.last_difficulty = GameDifficulty.Normal;
            }
            else if (s == Strings.Hard)
            {
                StateAndOptions.state.last_difficulty = GameDifficulty.Hard;
            }
            NewGamePage.start_new_game = true;
            GameType_List.SelectedItem = null;
            NavigationService.Navigate(new Uri("/Name.xaml", UriKind.Relative));
        }



        private void Global_Ranking_Button_Click(object sender, RoutedEventArgs e)
        {
            var hashalg = new SHA256Managed();

            WebBrowserTask browser = new WebBrowserTask();
            byte[] id = (byte[])Microsoft.Phone.Info.DeviceExtendedProperties.GetValue("DeviceUniqueId");
            var idh = hashalg.ComputeHash(id.Concat(Encoding.UTF8.GetBytes("tap")).ToArray());
            var phoneId = BitConverter.ToString(idh).Replace("-", "").ToLower();

            browser.URL = "http://chainingexpwp7.altervista.org/TapSequence.php?phoneID="+phoneId;
            browser.Show();
        }

        private void PivotControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //if (PivotControl.SelectedItem == ScoresPivot_Name)
            //{
            //    if (Global_Ranking == "")
            //        Global_Ranking_Button.Content = Strings.GlobalRank;
            //    else
            //        Global_Ranking_Button.Content = Strings.GlobalRank + ": " + Global_Ranking;
            //}

            if (PivotControl.SelectedItem == GlobalScoresPivot_Name)
            {
                var hashalg = new SHA256Managed();

                byte[] id = (byte[])Microsoft.Phone.Info.DeviceExtendedProperties.GetValue("DeviceUniqueId");
                var idh = hashalg.ComputeHash(id.Concat(Encoding.UTF8.GetBytes("tap")).ToArray());
                var phoneId = BitConverter.ToString(idh).Replace("-", "").ToLower();

                webBrowser1.Navigate(new Uri("http://chainingexpwp7.altervista.org/TapSequence.php?phoneID=" + phoneId));
            }
        }



        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            if (showProducts)
            {
                showProducts = false;
                Ads1_Button_Click(null, null);
            }
            if (showScores)
            {
                showScores = false;
                PivotControl.SelectedItem = ScoresPivot_Name;
            }
        }

    }


    public class GameStatus
    {
        public Color secret_color;
        public Color current_color;
        public int tests;
        public GameDifficulty difficulty;
        public long timeSpan_Ticks;
        public int helps = 0;
        public bool enableTimer;
        [XmlIgnore]
        public TimeSpan timer
        {
            get
            {
                return new TimeSpan(timeSpan_Ticks);
            }
            set
            {
                timeSpan_Ticks = value.Ticks;
            }
        }
        public GameStatus()
        {
            secret_color = new Color();
            current_color = new Color();
            tests = 0;
            timeSpan_Ticks = 0;
            difficulty = GameDifficulty.Normal;
            enableTimer = false;
        }
    }
}